//--------------------------------------------------- // Purpose: To demonstrate the implementation and use // of finite state machines using 2D arrays. // Author: John Gauch //--------------------------------------------------- #include using namespace std; // Program constants const int STATES = 5; const int INPUTS = 4; //--------------------------------------------------- // Print the 2D table representing finite state machine //--------------------------------------------------- void print_table(int table[STATES][INPUTS]) { // Print values cout << " "; for (int input = 0; input < INPUTS; input++) cout << char('a' + input) << " "; cout << endl; // Print line cout << " +"; for (int count = 0; count < INPUTS; count++) cout << "---+"; cout << "\n"; // Print state table for (int state = 0; state < STATES; state++) { // Print values cout << " " << state << " | "; for (int input = 0; input < INPUTS; input++) cout << table[state][input] << " | "; cout << endl; // Print line cout << " +"; for (int count = 0; count < INPUTS; count++) cout << "---+"; cout << "\n"; } } //--------------------------------------------------- // Interactively travese the finite state machine //--------------------------------------------------- void explore_table(int table[STATES][INPUTS], int start, int end) { // Use state table int state = start; cout << "state = " << state << endl; while (state != end) { // Get user input char dir = ' '; int input = INPUTS; while (input < 0 || input >= INPUTS) { cout << "Enter direction ['a'..'" << char('a'+INPUTS-1) << "']: "; cin >> dir; input = dir - 'a'; } // Move to new state state = table[state][input]; cout << "state = " << state << endl; } // Print final message cout << "You win!\n"; } //--------------------------------------------------- // Main program //--------------------------------------------------- int main() { // Define state table int start = 0; int end = 0; int table[STATES][INPUTS] = { {1,2,3,4}, {2,3,4,0}, {3,4,0,1}, {4,0,1,2}, {0,1,2,3} }; // Print state table print_table(table); // Explore state table cout << "Enter start state: "; cin >> start; cout << "Enter end state: "; cin >> end; explore_table(table, start, end); return 0; }